const app = getApp();
const QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
const qqmapsdk = new QQMapWX({
  key: 'QQBBZ-2ZGCJ-CCVF6-FRVFH-KA6SF-DIF3M' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //选项选中的城市
    city: '',
    city_id: null,
    //产品数据
    productList: [],
    //风格数据
    styleList: [],
    //检索数据
    queryString: {
      page: 1, //页码
      search: '',//检索
      // bedqty: 0, //床铺
      // city_id: null, //城市ID
      // cityname: '', //城市名称
      // landmarkid: 0, //地标ID
      // orderby: 0, //排序0=推荐排序，1=好评，2=价格升序，3=间隔降序
      // personqty: 0, //入住人数
      // roomqty: 0, //卧室数量
      // vipid: 0, //会员ID
      // producttypeid: 0, //分类ID
      // productstyleid: 0, //风格ID
    },
  },
  observers: {

    // 监听城市
    'city_id'(data) {
      this.setData({
        city_id: data
      })
      console.log(data);
      this.getData();
    }

  },

  jumpPage(event) {
    if ('landmark' == event.currentTarget.dataset.mark) {
      if (!wx.getStorageSync('city_id')) return app.tips('请先选择城市');
    }
    this.setData({
      productList: [],
      'queryString.page': 1
    });
    app.navigateTo(event.currentTarget.dataset.url)
  },
  /**
   * 确认风格--发起检索
   */
  confirmStyle(event) {
    let styleId = event.currentTarget.dataset.id;
    let query = this.data.queryString;
    if (styleId == query.style_id) {
      delete query.style_id;
    } else {
      query.style_id = styleId;
    }
    query.page = 1;
    this.setData({
      queryString: query,
      productList: []
    })
    this.getData();
  },

  /**
   * 获取民宿列表；
   */
  getData() {
    let _this = this;
    app.loading();
    let query = _this.data.queryString;
    if (_this.data.city_id) {
      query.city_id = _this.data.city_id;
    }
    app.HttpsRequest('product/getList', 'GET', query).then(ret => {
      wx.hideLoading();
      let productList = _this.data.productList ? _this.data.productList : [] ;
      for (let key in ret.data.product) {
        productList.push(ret.data.product[key]);
      }
      _this.setData({
        productList: productList,
        styleList: ret.data.style,
        'queryString.page': _this.data.queryString.page + 1
      });
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(options) {
    let _this = this;
    _this.setQueryString();
    _this.getData();
  },

  /**
   * 输入绑定
   */
  onInput(event){
    this.setData({
      'queryString.search': event.detail
    })
  },

  /**
   * 搜索
   */
  onSearch(event) {
    this.setData({
      'queryString.page': 1,
      productList: []
    });
    this.getData();
  },
  /**
   * 获取缓存设置
   */
  setQueryString() {
    let _this = this;
    _this.setData({
      city: wx.getStorageSync('city')
    });
    if (!wx.getStorageSync('city')) {
      let that = this;
      wx.getSetting({
        success: (res) => {
          // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
          // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
          // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
            wx.showModal({
              title: '请求授权当前位置',
              content: '需要获取您的地理位置，请确认授权',
              success: function (res) {
                if (res.cancel) {
                  wx.showToast({
                    title: '拒绝授权',
                    icon: 'none',
                    duration: 1000
                  })
                } else if (res.confirm) {
                  wx.openSetting({
                    success: function (dataAu) {
                      if (dataAu.authSetting["scope.userLocation"] == true) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 1000
                        })
                        //再次授权，调用wx.getLocation的API
                        that.getLocation();
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    }
                  })
                }
              }
            })
          } else if (res.authSetting['scope.userLocation'] == undefined) {
            //调用wx.getLocation的API
            that.getLocation();
          }
          else {
            //调用wx.getLocation的API
            that.getLocation();
          }
        }
      })
    }
    let query = {page: 1, search: ''};
    if (wx.getStorageSync('category_id')) {
      query.category_id = wx.getStorageSync('category_id');
    }
    if (wx.getStorageSync('city_id')) {
      query.city_id = wx.getStorageSync('city_id');
    }
    if (wx.getStorageSync('orderby')) {
      query.orderby = wx.getStorageSync('orderby');
    }
    if (wx.getStorageSync('filter_id')) {
      query.filter_id = wx.getStorageSync('filter_id');
    }
    if (wx.getStorageSync('landmark_id')) {
      query.landmark_id = wx.getStorageSync('landmark_id');
    }
    if (wx.getStorageSync('style_id')) {
      query.style_id = wx.getStorageSync('style_id');
      wx.removeStorageSync('style_id');
    }
    _this.setData({
      queryString: query,
      productList: []
    })
  },

  // 获取定位当前位置的经纬度
  getLocation: function () {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        app.globalData.lat = res.latitude;//
        app.globalData.lng = res.longitude;//把onload定位时候的经纬度存到全局
        let speed = res.speed
        let accuracy = res.accuracy;
        that.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let that = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let city = res.result.ad_info.city
        app.HttpsRequest('product/getCityId', 'GET', {city: city}).then(ret => {
          wx.setStorageSync('city', city)
          wx.setStorageSync('city_id', ret.data.city_id)
          wx.hideLoading();
          let isSearch = that.data.city_id;
          that.setData({
            city: city,
            city_id: ret.data.city_id,
            productList: [],
            'queryString.page': 1
          })
          that.getData();
        })

      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },


  /**
   * 重置页面
   */
  reset() {
    wx.removeStorageSync('orderby');
    wx.removeStorageSync('filter_id');
    wx.removeStorageSync('landmark_id');
    wx.removeStorageSync('category_id');
    this.setData({
      queryString:{page:1}
    })
    this.getData();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.getData();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})